<template>
  <div>
    <div style="margin-bottom: 5px">
      <el-input v-model= "aname" placeholder="请输入群组名称" suffix-icon="search" style="width: 200px"/>
      <el-button id="11" type="primary" style="margin-left: 10px" @click = "search">查询</el-button>
      <el-button id="12" type="success" @click = "reset">重置</el-button>
      <el-button id="13" type="primary" style="margin-left: 10px" @click = "add">新增</el-button>
<!--      <div class="function-point-container">-->
        <!-- 批量导入 -->
        <el-button
            type="primary"
            @click="$refs.excelBtn.click()"
        >批量导入</el-button>
        <el-upload
            v-show="false"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
            action
            :auto-upload="false"
            :show-file-list="false"
            :on-change="importData"
        >
          <span ref="excelBtn">导入EXCEL</span>
        </el-upload>
<!--      </div>-->
    </div>
    <el-scrollbar>
      <el-table :data="tableData">
        <el-table-column type="index" width="200px" label="序号"/>
        <el-table-column prop="answerName" label="名称"/>
        <el-table-column prop="phone" label="电话"/>
        <el-table-column prop="age" label="年龄"/>
        <el-table-column prop="gender" label="性别"/>
        <el-table-column prop="address" label="地址"/>
        <el-table-column prop="operate" label="操作">
          <template #default="scope">
            <el-button size="small" type="warning" @click="mod(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="dele(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
    <el-dialog v-model="centerDialogVisible" title="新增/修改" width="30%" center>
      <el-form :model="form" label-width="120px" :rules="rules" ref = "form">
        <el-form-item label="答者名称" prop="answerName">
          <el-col span="20">
            <el-input v-model="form.answerName" />
          </el-col>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-col span="20">
            <el-input v-model="form.phone" />
          </el-col>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-col span="20">
            <el-input-number
                v-model="form.age"
                :min="1"
                :max="100"
                controls-position="right"
                size="small"
            />
          </el-col>
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-col span="20">
            <el-radio-group v-model="form.gender" class="ml-4">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
            </el-radio-group>
          </el-col>

        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-col span="20">
            <el-input v-model="form.address" />
          </el-col>
        </el-form-item>
        <el-form-item label="职业" prop="job">
          <el-col span="20">
            <el-input v-model="form.job" />
          </el-col>
        </el-form-item>
      </el-form>

      <template #footer>
      <span class="dialog-footer">
        <el-button type="danger" @click=quxiao>取消</el-button>
        <el-button type="primary" @click="addSave">确认</el-button>
      </span>
      </template>
    </el-dialog>
  </div>

</template>

<script>
  import * as XLSX from "xlsx";
  import request from "@/util/request";
  import {ElMessage} from "element-plus";
  export default {
    name: "Answer",
    data(){
      return {
        tableData:[],
        aname:'',
        ismod:false,
        centerDialogVisible:false,
        form:{
          answerName:'',
          phone:'',
          age:'',
          aid:'',
          gender:'',
          address:'',
          job:'',
          options:[
            {
              label:'男',
              value:'男'
            },
            {
              label:'女',
              value:'女'
            }
          ]
        },
        rules:{
          answerName : [
            {required:true, message:'请输入名字',trigger:'blur'},
            {min:3, max:8, message: '请输入长度1-8字符', trigger: 'blur'},
          ],
          phone : [
            {required:true, message:'请输入电话',trigger:'blur'},
            {min:3, max:8, message: '请输入正确的电话号码', trigger: 'blur',pattern: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/}
          ],
          age : [
            {required:true, message:'请输入年龄',trigger:'blur'}
          ],
          gender : [
            {required:true, message:'请选择性别',trigger:'blur'}
          ],
          address : [
            {required:true, message:'请输入地址',trigger:'blur'},
            {min:3, max:8, message: '请输入长度3-8字符', trigger: 'blur'},
          ],
          job : [
            {required:true, message:'请输入职业',trigger:'blur'}
          ]
        }
      }
    },
    created() {},
    methods : {

      loadPost() {
        let name = this.aname
        // formData.append("kind",this.pname);
        // formData.append("uid",this.getValue().uid);
        request.post("http://localhost:8090/answer/findAnswerByAnswerName",{
            answerName:name
        }).then(res=>res.data).then(res =>{
          this.tableData = res.data
          console.log(this.tableData)
        });

      },
      search() {
        this.loadPost()
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      add() {
        this.ismod=false
        this.form=[]
        this.centerDialogVisible=true
        this.resetForm('form')
      },
      dele(low) {
        let name = low.answerName
        console.log(low)
        this.$axios.post("http://localhost:8090/answer/deleteAnswer",{
          answerName:name,
          aid:low.aid
        }).then(res=>res.data).then(res =>{
          if(res.code == '200') {
            ElMessage({
              message: '操作成功！',
              type: 'success',
            })
            this.loadPost()
          }else {
            console.log(res)
            // ElMessage({
            //   message: '该答者在群组中，无法删除！',
            //   type: 'error',
            // })
          }
          console.log(res)
        });
      },
      addSave() {
        this.$refs.form.validate(valid=>{
          if (valid) {
            let self = this
            let pform = this.form
            console.log("表格是：")
            console.log(pform)
            if (this.ismod) {

              request.post("http://localhost:8090/answer/updateAnswer",{
                answerName:pform.answerName,
                password:'123',
                phone:pform.phone,
                age:pform.age,
                gender:pform.gender,
                address:pform.address,
                job:pform.job,
                aid:pform.aid
              }).then(res=>res.data).then(res =>{
                if (res.code == '200') {
                  ElMessage({
                    message: '修改成功！',
                    type: 'success',
                  })
                }else{
                  ElMessage({
                    message: '修改失败！',
                    type: 'error',
                  })
                }
                self.centerDialogVisible=false
                self.loadPost();
              });

            }else {

              request.post("http://localhost:8090/answer/addAnswer",{
                answerName:pform.answerName,
                password:'123',
                phone:pform.phone,
                age:pform.age,
                gender:pform.gender,
                address:pform.address,
                job:pform.job,
              }).then(res=>res.data).then(res =>{
                if (res.code == '200') {
                  ElMessage({
                    message: '添加成功！',
                    type: 'success',
                  })
                }else{
                  ElMessage({
                    message: '添加失败！',
                    type: 'error',
                  })
                }
                self.centerDialogVisible=false
                self.loadPost();
              });
            }
          }
        })
      },
      quxiao() {
        this.centerDialogVisible=false
      },
      reset() {
        this.aname=''
      },
      importData(file, fileList) {
        // 拿取文件对象
        const f = file.raw
        // 用 FileReader 来读取
        let reader = new FileReader()
        let self = this
        let i=0
        // 重写 FileReader 上的 readAsBinaryString 方法
        FileReader.prototype.readAsBinaryString = f => {
          let binary = ''
          let wb // 读取完成的数据
          let outdata // 你需要的数据
          let reader = new FileReader()
          reader.onload = e => {
            // 读取成Uint8Array，再转换为Unicode编码（Unicode占两个字节）
            let bytes = new Uint8Array(reader.result)
            let length = bytes.byteLength
            for (let i = 0; i < length; i++) {
              binary += String.fromCharCode(bytes[i])
            }
            // 接下来就是xlsx了，具体可看api
            wb = XLSX.read(binary, {
              type: 'binary',
              cellDates: false
            })
            outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
            const result = this.generateParam(outdata)
            console.log(result.size)
            console.log('result--', result)
            result.forEach(function (item) {
              i++
              request.post("http://localhost:8090/answer/addAnswer",item).then(res=>res.data).then(res =>{
                console.log(res)
                self.loadPost()
              });
            })
            while(i<result.length){
              console.log(i)
            }

          }
          reader.readAsArrayBuffer(f)

        }
        reader.readAsBinaryString(f)

      },
      mod(low){
        console.log(low)
        this.$axios.post()
        this.ismod=true
        this.form.age=low.age
        this.form.phone=low.phone
        this.form.answerName=low.answerName
        this.form.address=low.address
        this.form.aid=low.aid
        this.form.gender=low.gender
        this.form.job=low.job
        this.centerDialogVisible=true
      },
      // 生成导入参数
      generateParam(data) {
        const params = []
        // 这里根据实际表格 title 值、接口参数值，灵活变化
        const parse = {
          姓名: 'answerName',
          密码: 'password',
          手机号: 'phone',
          年龄: 'age',
          性别: 'gender',
          地址: 'address',
          工作: 'job'
        }
        data.forEach(item => {
          let obj = {}
          const keys = Object.keys(parse)
          const itemKeys = Object.keys(item)
          itemKeys.forEach(key => {
            const val = item[key]
            if (keys.includes(key)) {
              obj[parse[key]] = val
            }
          })
          params.push(obj)
        })
        return params
      }
    },
    beforeMount() {
      this.loadPost()
    }
  }
</script>

<style scoped>
.layout-container-demo .el-header {
  position: relative;
  background-color: var(--el-color-primary-light-7);
  color: var(--el-text-color-primary);
}
.layout-container-demo .el-aside {
  color: var(--el-text-color-primary);
  background: var(--el-color-primary-light-8);
}
.layout-container-demo .el-menu {
  border-right: none;
}
.layout-container-demo .el-main {
  padding: 0;
}
.layout-container-demo .toolbar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  right: 20px;
}
</style>